package com.netsdk.demo.customize;

import com.netsdk.demo.util.CaseMenu;
import com.netsdk.lib.NetSDKLib;
import com.netsdk.lib.ToolKits;
import com.netsdk.lib.callback.impl.DefaultDisconnectCallback;
import com.netsdk.lib.callback.impl.DefaultHaveReconnectCallBack;
import com.netsdk.lib.callback.securityCheck.PackageInformationCallBack;
import com.netsdk.lib.enumeration.*;
import com.netsdk.lib.structure.*;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;
import static com.netsdk.lib.Utils.getOsPrefix;

/**
 * @author 291189
 * @version 1.0
 * @description ERR230417082 & GIP230705005
 * @date 2023/4/18 9:23
 */
public class XrayDetectionNewDemo {

    // SDk对象初始化
    public static final NetSDKLib netsdk = NetSDKLib.NETSDK_INSTANCE;
    public static final NetSDKLib configsdk = NetSDKLib.CONFIG_INSTANCE;

    // 判断是否初始化
    private static boolean bInit = false;
    // 判断log是否打开
    private static boolean bLogOpen = false;
    // 设备信息
    private NetSDKLib.NET_DEVICEINFO_Ex deviceInfo = new NetSDKLib.NET_DEVICEINFO_Ex();
    // 登录句柄
    private static NetSDKLib.LLong m_hLoginHandle = new NetSDKLib.LLong(0);


    // 回调函数需要是静态的，防止被系统回收
    // 断线回调
    private static NetSDKLib.fDisConnect disConnectCB = DefaultDisconnectCallback.getINSTANCE();
    // 重连回调
    private static NetSDKLib.fHaveReConnect haveReConnectCB = DefaultHaveReconnectCallBack.getINSTANCE();

    // 编码格式
    public static String encode;

    static {
        String osPrefix = getOsPrefix();
        if (osPrefix.toLowerCase().startsWith("win32-amd64")) {
            encode = "GBK";
        } else if (osPrefix.toLowerCase().startsWith("linux-amd64")) {
            encode = "UTF-8";
        }
    }

    /**
     * 获取当前时间
     */
    public static String GetDate() {
        SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDate.format(new java.util.Date()).replaceAll("[^0-9]", "-");
    }

    /**
     * 初始化SDK库
     */
    public static boolean Init() {
        bInit = netsdk.CLIENT_Init(disConnectCB, null);// 进程启动时，初始化一次
        if (!bInit) {
            System.out.println("Initialize SDK failed");
            return false;
        }
        // 配置日志
        XrayDetectionNewDemo.enableLog();

        // 设置断线重连回调接口, 此操作为可选操作，但建议用户进行设置
        netsdk.CLIENT_SetAutoReconnect(haveReConnectCB, null);

        // 设置登录超时时间和尝试次数，可选
        // 登录请求响应超时时间设置为3S
        int waitTime = 3000;
        // 登录时尝试建立链接 1 次
        int tryTimes = 1;
        netsdk.CLIENT_SetConnectTime(waitTime, tryTimes);
        // 设置更多网络参数， NET_PARAM 的nWaittime ， nConnectTryNum 成员与 CLIENT_SetConnectTime
        // 接口设置的登录设备超时时间和尝试次数意义相同,可选
        NetSDKLib.NET_PARAM netParam = new NetSDKLib.NET_PARAM();
        // 登录时尝试建立链接的超时时间
        netParam.nConnectTime = 10000;
        // 设置子连接的超时时间
        netParam.nGetConnInfoTime = 3000;
        netsdk.CLIENT_SetNetworkParam(netParam);
        return true;
    }

    /**
     * 打开 sdk log
     */
    private static void enableLog() {
        NetSDKLib.LOG_SET_PRINT_INFO setLog = new NetSDKLib.LOG_SET_PRINT_INFO();
        File path = new File("sdklog/");
        if (!path.exists())
            path.mkdir();

        // 这里的log保存地址依据实际情况自己调整
        String logPath = path.getAbsoluteFile().getParent() + "\\sdklog\\" + "sdklog" + GetDate() + ".log";
        setLog.nPrintStrategy = 0;
        setLog.bSetFilePath = 1;
        System.arraycopy(logPath.getBytes(), 0, setLog.szLogFilePath, 0, logPath.getBytes().length);
        System.out.println(logPath);
        setLog.bSetPrintStrategy = 1;
        bLogOpen = netsdk.CLIENT_LogOpen(setLog);
        if (!bLogOpen)
            System.err.println("Failed to open NetSDK log");
    }

    /**
     * 高安全登录
     */
    public void loginWithHighLevel() {
        // 输入结构体参数
        NetSDKLib.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY pstlnParam = new NetSDKLib.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY() {
            {
                szIP = m_strIpAddr.getBytes();
                nPort = m_nPort;
                szUserName = m_strUser.getBytes();
                szPassword = m_strPassword.getBytes();
            }
        };
        // 输出结构体参数
        NetSDKLib.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY pstOutParam = new NetSDKLib.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY();

        // 写入sdk
        m_hLoginHandle = netsdk.CLIENT_LoginWithHighLevelSecurity(pstlnParam, pstOutParam);
        if (m_hLoginHandle.longValue() == 0) {
            System.err.printf("Login Device[%s] Port[%d]Failed. %s\n", m_strIpAddr, m_nPort,
                    netsdk.CLIENT_GetLastError());
        } else {
            deviceInfo = pstOutParam.stuDeviceInfo; // 获取设备信息
            System.out.println("Login Success");
            System.out.println("Device Address：" + m_strIpAddr);
            System.out.println("设备包含：" + deviceInfo.byChanNum + "个通道");
        }
    }

    /**
     * 退出
     */
    public void logOut() {
        if (m_hLoginHandle.longValue() != 0) {
            netsdk.CLIENT_Logout(m_hLoginHandle);
            System.out.println("LogOut Success");
        }
    }

    /**
     * 清理sdk环境并退出
     */
    public static void cleanAndExit() {
        if (bLogOpen) {
            netsdk.CLIENT_LogClose(); // 关闭sdk日志打印
        }
        netsdk.CLIENT_Cleanup(); // 进程关闭时，调用一次
        System.exit(0);
    }


    public static Pointer GetStringToPointer(String src, String charset) {
        Pointer pointer = null;
        try {
            byte[] b = src.getBytes(charset);

            pointer = new Memory(b.length + 1);
            pointer.clear(b.length + 1);

            pointer.write(0, b, 0, b.length);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return pointer;
    }

    //当只有一个通道的时候填0
    int channel=-1;

    NetSDKLib.LLong    attachHandle=new NetSDKLib.LLong(0);
    /**
     * 订阅智能任务
     */

    public NetSDKLib.LLong AttachEventRealLoadPic() {
        // 先退订，设备不会对重复订阅作校验，重复订阅后会有重复的事件返回
        if(attachHandle.longValue()!=0){
            this.DetachEventRealLoadPic();
        }

        // 需要图片
        int bNeedPicture = 1;
        attachHandle = netsdk.CLIENT_RealLoadPictureEx(m_hLoginHandle, channel, NetSDKLib.EVENT_IVS_ALL, bNeedPicture,
                AnalyzerDataCB.getInstance(), null, null);
        if (attachHandle.longValue() != 0) {
            System.out.printf("Chn[%d] CLIENT_RealLoadPictureEx Success\n", channel);
        } else {
            System.out.printf("Chn[%d] CLIENT_RealLoadPictureEx Failed!LastError = %s\n", channel,
                    ToolKits.getErrorCode());
        }

        return attachHandle;
    }
    /**
     * 报警事件（智能）回调
     */
    private static class AnalyzerDataCB implements NetSDKLib.fAnalyzerDataCallBack {
        private final File picturePath;
        private static AnalyzerDataCB instance;

        private AnalyzerDataCB() {
            picturePath = new File("./AnalyzerPicture/");
            if (!picturePath.exists()) {
                picturePath.mkdirs();
            }
        }

        public static AnalyzerDataCB getInstance() {
            if (instance == null) {
                synchronized (AnalyzerDataCB.class) {
                    if (instance == null) {
                        instance = new AnalyzerDataCB();
                    }
                }
            }
            return instance;
        }

        @Override
        public int invoke(NetSDKLib.LLong lAnalyzerHandle, int dwAlarmType, Pointer pAlarmInfo, Pointer pBuffer, int dwBufSize,
                          Pointer dwUser, int nSequence, Pointer reserved) {
            if (lAnalyzerHandle == null || lAnalyzerHandle.longValue() == 0) {
                return -1;
            }

            switch (Objects.requireNonNull(EM_EVENT_IVS_TYPE.getEventType(dwAlarmType))) {
                case EVENI_IVS_XRAY_DETECTION : {
                    System.out.println("X光检测事件");

                    DEV_EVENT_XRAY_DETECTION_INFO msg = new DEV_EVENT_XRAY_DETECTION_INFO();

                    ToolKits.GetPointerData(pAlarmInfo, msg);
                    // 通道号
                    int nChannelID = msg.nChannelID;
                    System.out.println("nChannelID:" + nChannelID);
                    //事件名称
                    byte[] szName = msg.szName;
                    System.out.println("szName:" + new String(szName));
                    //相对事件时间戳(单位是毫秒)
                    double pts = msg.PTS;
                    System.out.println("pts:" + new Date((long) pts));
                    //UTC时间
                    NET_TIME_EX UTC = msg.UTC;
                    System.out.println("UTC:" + UTC.toStringTime());
                    //所属大类
                    int emClassType = msg.emClassType;
                    System.out.println("emClassType:" + emClassType);
                    //事件id
                    int nEventID = msg.nEventID;
                    System.out.println("nEventID:" + nEventID);
                    //危险等级
                    int emDangerGrade = msg.stuPacketInfo.emDangerGrade;
                    System.out.println("stuPacketInfo.emDangerGrade:" + emDangerGrade);
                    //主视角包裹内物品个数
                    int nObjectNum = msg.nObjectNum;
                    System.out.println("nObjectNum:" + nObjectNum);
                    // 主视角包裹内物品信息
                    for(int i = 0; i < nObjectNum; i ++){
                        NET_INSIDE_OBJECT stuInsideObj = msg.stuInsideObj[i];

                        /**
                         *  物品类型  {@link com.netsdk.lib.enumeration.EM_INSIDE_OBJECT_TYPE}
                         */
                        System.out.println("["+i+"]物品类型:" + EM_INSIDE_OBJECT_TYPE.getNoteByValue(stuInsideObj.emObjType) );
                        /**
                         *  物品危险等级 {@link com.netsdk.lib.NetSDKLib.EM_DANGER_GRADE_TYPE }
                         */
                        System.out.println("["+i+"]物品危险等级:" + stuInsideObj.emDangerGrade );

                        System.out.println("["+i+"]相似度:" + stuInsideObj.nSimilarity );

                        try {
                            System.out.println("["+i+"]自定义物品类型 (emObjType为 EM_INSIDE_OBJECT_UNKNOWN 时使用):" + new String(stuInsideObj.szObjectType,encode) );
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                    //从视角包裹内物品个数
                    int nSlaveViewObjectNum = msg.nSlaveViewObjectNum;
                    System.out.println("nSlaveViewObjectNum:" + nSlaveViewObjectNum);
                    // 从视角包裹内物品信息
                    for(int i = 0; i < nSlaveViewObjectNum; i ++){
                        NET_INSIDE_OBJECT stuSlaveViewInsideObj = msg.stuSlaveViewInsideObj[i];
                        System.out.println("stuSlaveViewInsideObj["+i+"]:" + stuSlaveViewInsideObj.toString());
                    }
                    //图片数量
                    int nImageCount = msg.nImageCount;
                    System.out.println("nImageCount:" + nImageCount);
                    int picSizes = 0;
                    // 图片信息
                    for(int i = 0; i < nImageCount; i ++){
                        NET_XRAY_IMAGE_INFO stuImageInfo = msg.stuImageInfo[i];
                        System.out.println("stuImageInfo["+i+"]:" + stuImageInfo.toString());
                        //图片
                        if (stuImageInfo != null && stuImageInfo.nLength > 0) {

                            picSizes += stuImageInfo.nLength;

                            String picture = picturePath + "\\" + System.currentTimeMillis() + "related.jpg";
                            ToolKits.savePicture(pBuffer, stuImageInfo.nOffset, stuImageInfo.nLength, picture);
                        }
                    }

                    // 客户自定义信息个数
                    int nViewCustomInfoNum = msg.nViewCustomInfoNum;
                    System.out.println("nViewCustomInfoNum:" + nViewCustomInfoNum);
                    // 客户自定义信息, X光机
                    for(int i = 0; i < nViewCustomInfoNum; i ++){
                        NetSDKLib.NET_XRAY_CUSTOM_INFO stuViewCustomInfo = msg.stuViewCustomInfo[i];
                        System.out.println("stuViewCustomInfo["+i+"]:" + stuViewCustomInfo.toString());
                    }
                    // 包裹标识
                    String szPackageTag = Arrays.toString(msg.szPackageTag);
                    System.out.println("szPackageTag:" + szPackageTag);
                    // 包裹产生方式
                    int emPackageMode = msg.emPackageMode;
                    System.out.println("emPackageMode:" + emPackageMode);
                    // 关联图片数量
                    int nRelatedImageNum = msg.nRelatedImageNum;
                    System.out.println("nRelatedImageNum:" + nRelatedImageNum);
                    // 客户自定义信息, X光机
                    for(int i = 0; i < nRelatedImageNum; i ++){
                        NET_XRAY_RELATED_IMAGE_INFO stuRelatedImageInfo = msg.stuRelatedImageInfo[i];
                        System.out.println("stuRelatedImageInfo["+i+"]:" + stuRelatedImageInfo.toString());
                        //图片  stuRelatedImageInfo
                        if (stuRelatedImageInfo != null && stuRelatedImageInfo.nLength > 0) {

                            picSizes += stuRelatedImageInfo.nLength;

                            String picture = picturePath + "\\" + System.currentTimeMillis() + "related2.jpg";
                            ToolKits.savePicture(pBuffer, stuRelatedImageInfo.nOffset, stuRelatedImageInfo.nLength, picture);
                        }
                    }
                    break;
                }
                case EVENT_IVS_XRAY_UNPACKING_CHECK : {// X光开包检查事件 对应DEV_EVENT_XRAY_UPACKING_CHECK_INFO
                    System.out.println("X光开包检查事件");

                    DEV_EVENT_XRAY_UNPACKING_CHECK_INFO msg = new DEV_EVENT_XRAY_UNPACKING_CHECK_INFO();

                    ToolKits.GetPointerData(pAlarmInfo, msg);
                    // 通道号
                    int nChannelID = msg.nChannelID;
                    System.out.println("nChannelID:" + nChannelID);
                    //事件动作,0表示脉冲事件
                    int nAction = msg.nAction;
                    System.out.println("nAction:" + nAction);
                    //事件名称
                    byte[] szName = msg.szName;
                    System.out.println("szName:" + new String(szName));
                    //智能事件所属大类
                    byte[] szClass = msg.szClass;
                    System.out.println("szClass:" + new String(szClass));
                    //相对事件时间戳(单位是毫秒)
                    double pts = msg.PTS;
                    System.out.println("pts:" + new Date((long) pts));
                    //开包检查信息
                    UNPACKING_CHECK_INFO stuCheckInfo = msg.stuCheckInfo;
                    //事件发生时间，带时区偏差的UTC时间，单位秒
                    int nUTC = stuCheckInfo.nUTC;
                    System.out.println("nUTC:" + new Date(nUTC * 1000));
                    //事件时间毫秒数
                    int nUTCMS = stuCheckInfo.nUTCMS;
                    System.out.println("nUTCMS:" + new Date(nUTCMS));
                    //表示包裹标识，用来唯一标识一个包裹
                    byte[] szPackageTag = stuCheckInfo.szPackageTag;
                    System.out.println("szPackageTag:" + new String(szPackageTag));
                    //关联图片
                    RELATED_IMAGE[] stuRelatedImages = stuCheckInfo.stuRelatedImage;

                    int nRelatedImageRetNum = stuCheckInfo.nRelatedImageRetNum;


                    int picSizes=0;

                    for (int i = 0; i < nRelatedImageRetNum; i++) {
                        RELATED_IMAGE stuRelatedImage = stuRelatedImages[i];
                        //图片
                        if (stuRelatedImage != null && stuRelatedImage.nLength > 0) {

                            picSizes += stuRelatedImage.nLength;

                            String picture = picturePath + "\\" + System.currentTimeMillis() + "related.jpg";
                            ToolKits.savePicture(pBuffer, stuRelatedImage.nOffset, stuRelatedImage.nLength, picture);
                        }

                    }

                    //身份信息
                    IDENTITY_INFO stuIdentityInfo = stuCheckInfo.stuIdentityInfo;
                    //法定姓名
                    byte[] szCitizenName = stuIdentityInfo.szCitizenName;
                    System.out.println("szCitizenName:" + new String(szCitizenName));
                    //证件号18位
                    byte[] szCitizenIDNo = stuIdentityInfo.szCitizenIDNo;
                    System.out.println("szCitizenIDNo:" + new String(szCitizenIDNo));
                    //性别
                    int emSex = stuIdentityInfo.emSex;
                    System.out.println("emSex:" + emSex);
                    //年龄
                    int nAge = stuIdentityInfo.nAge;
                    System.out.println("nAge:" + nAge);

                    //违禁物品个数
                    int nContrabandRetNum
                            = stuCheckInfo.nContrabandRetNum;
                    System.out.println("nContrabandRetNum:" + nContrabandRetNum);

                    /**
                     * 违禁物品分类  {@link com.netsdk.lib.enumeration.EM_INSIDE_OBJECT_TYPE}
                     */

                    int[] emContrabandClass
                            = stuCheckInfo.emContrabandClass;

                    for (int i = 0; i < nContrabandRetNum; i++) {

                        System.out.println("违禁物品分类["+i+"]" + EM_INSIDE_OBJECT_TYPE.getNoteByValue(emContrabandClass[i]));
                    }

                    //处理方式
                    int emProcessMode = stuCheckInfo.emProcessMode;
                    System.out.println("emProcessMode:" + emProcessMode);
                    //检出人，即开包人员
                    byte[] szChecker = stuCheckInfo.szChecker;
                    System.out.println("szChecker:" + new String(szChecker));
                    //报警地点
                    byte[] szAlarmLocation = stuCheckInfo.szAlarmLocation;
                    System.out.println("szAlarmLocation:" + new String(szAlarmLocation));
                    //报警时间（即拍摄违禁品时间），UTC时间，单位秒
                    int nAlarmTime = stuCheckInfo.nAlarmTime;
                    System.out.println("nAlarmTime:" + new Date(nAlarmTime * 1000));
                    //行程出发地
                    byte[] szPlaceOfDeparture = stuCheckInfo.szPlaceOfDeparture;
                    System.out.println("szPlaceOfDeparture:" + new String(szPlaceOfDeparture));
                    //行程目的地
                    byte[] szDestination = stuCheckInfo.szDestination;
                    System.out.println("szDestination:" + new String(szDestination));


                    break;
                }
                default:
                    System.out.println("其他事件--------------------"+ dwAlarmType);
                    break;
            }
            return 0;
        }
    }


    /**
     * 停止侦听智能事件
     */
    public void DetachEventRealLoadPic() {
        if (this.attachHandle.longValue() != 0) {
            netsdk.CLIENT_StopLoadPic(this.attachHandle);
        }
    }
    // 订阅句柄
    private static NetSDKLib.LLong XRayAttachHandle = new NetSDKLib.LLong(0);

    /**
     *    订阅X光机包裹数量统计信息
     */

    public void attachPackageStatistics(){
        //入参
        NET_IN_XRAY_ATTACH_PACKAGE_STATISTICS inParam=new NET_IN_XRAY_ATTACH_PACKAGE_STATISTICS();

        UUID uuid= UUID.randomUUID();
        byte[] szUUID = inParam.szUUID;

        String numbers =uuid.toString();
        //beda31a3-a7b5-4126-81b9-6e67402b7b0c?
        int i = numbers.lastIndexOf("-");

        String[] split = numbers.split("-");
        //UUID算法(8-4-4-16格式)

        numbers=split[0]+"-"+split[1]+""+split[2]+"-"+split[3]+split[4];

        System.arraycopy(numbers.getBytes(), 0, szUUID, 0, numbers.getBytes().length);

        inParam.szUUID=szUUID;

        Pointer user=new Memory(1024);
        inParam.dwUser=user;
        inParam.cbNotify= PackageInformationCallBack.getInstance();
        Pointer pInParam=new Memory(inParam.size());
        ToolKits.SetStructDataToPointer(inParam, pInParam, 0);

        //出参
        NET_OUT_XRAY_ATTACH_PACKAGE_STATISTICS outParm=new NET_OUT_XRAY_ATTACH_PACKAGE_STATISTICS();

        Pointer pOutParam=new Memory(outParm.size());
        ToolKits.SetStructDataToPointer(outParm, pOutParam, 0);

        XRayAttachHandle=  netsdk.CLIENT_XRayAttachPackageStatistics(m_hLoginHandle,pInParam,pOutParam,3000);

        if (XRayAttachHandle.longValue() != 0) {
            System.out.println("CLIENT_XRayAttachPackageStatistics Success");
        } else {
            System.out.println("CLIENT_XRayAttachPackageStatistics Failed!LastError = %s\n"+ToolKits.getErrorCode());
        }
    }

    /**
     * 取消订阅X光机包裹数量统计信息
     */
    public void DetachPackageStatistics() {
        if (XRayAttachHandle.longValue() != 0) {
            netsdk.CLIENT_XRayDetachPackageStatistics(XRayAttachHandle);
        }
    }

    NET_XRAY_MULTILEVEL_DETECT_CFG_INFO stuInfo = new NET_XRAY_MULTILEVEL_DETECT_CFG_INFO();

    public void getXRayMultiLevelDetectCFG() {
        NET_IN_GET_XRAY_MULTILEVEL_DETECT_INFO input = new NET_IN_GET_XRAY_MULTILEVEL_DETECT_INFO();
        Pointer pointerInput = new Memory(input.size());
        pointerInput.clear(input.size());
        ToolKits.SetStructDataToPointer(input, pointerInput, 0);

        NET_OUT_GET_XRAY_MULTILEVEL_DETECT_INFO outPut = new NET_OUT_GET_XRAY_MULTILEVEL_DETECT_INFO();

        outPut.stuInfo = stuInfo;
        /**
         等级配置最大个数（用户配置）
         */
        stuInfo.nMultiLevelConfigMax = 10;

        NET_MULTI_LEVEL_INFO info = new NET_MULTI_LEVEL_INFO();
        /**
         * 等级配置 此部分内存需要用户申请,申请大小为(nMultiLevelConfigMax*sizeof(NET_MULTI_LEVEL_INFO))。
         */
        outPut.stuInfo.pstuMultiLevelConfig = new Memory(info.size() * outPut.stuInfo.nMultiLevelConfigMax);

        outPut.stuInfo.pstuMultiLevelConfig.clear(info.size() * outPut.stuInfo.nMultiLevelConfigMax);

        Pointer pointerOutPut = new Memory(outPut.size());
        pointerOutPut.clear(outPut.size());
        ToolKits.SetStructDataToPointer(outPut, pointerOutPut, 0);

        NetSDKLib.LLong lLong = netsdk.CLIENT_GetXRayMultiLevelDetectCFG(m_hLoginHandle, pointerInput, pointerOutPut,
                3000);
        if (lLong.longValue() != 0) {

            ToolKits.GetPointerData(pointerOutPut, outPut);

            Native.free(Pointer.nativeValue(pointerInput)); // 清理内存
            Pointer.nativeValue(pointerInput, 0); // 防止gc重复回收

            Native.free(Pointer.nativeValue(pointerOutPut));
            Pointer.nativeValue(pointerOutPut, 0);
            System.out.println("CLIENT_GetFinancialCabinInfo success");

            stuInfo = outPut.stuInfo;

            /**
             * 当前配置等级 {@link com.netsdk.lib.enumeration.EM_XRAY_OBJECT_DETECT_CONFIG_LEVEL}
             */
            System.out.println("emCurrentLevel:" + stuInfo.emCurrentLevel);

            System.out.println("nMultiLevelConfigMax:" + stuInfo.nMultiLevelConfigMax);

            int nMultiLevelConfigCnt = stuInfo.nMultiLevelConfigCnt;

            System.out.println("nMultiLevelConfigCnt:" + nMultiLevelConfigCnt);

            NET_MULTI_LEVEL_INFO[] infos = new NET_MULTI_LEVEL_INFO[nMultiLevelConfigCnt];
            for (int i = 0; i < infos.length; i++) {
                infos[i] = new NET_MULTI_LEVEL_INFO();
            }

            ToolKits.GetPointerDataToStructArr(stuInfo.pstuMultiLevelConfig, infos);

            for (int i = 0; i < infos.length; i++) {
                NET_MULTI_LEVEL_INFO info1 = infos[i];

                /**
                 * 配置等级 {@link com.netsdk.lib.enumeration.EM_XRAY_OBJECT_DETECT_CONFIG_LEVEL}
                 */
                System.out.println("emLevel:" + info1.emLevel);

                /**
                 * 默认参考等级，该等级的默认配置与参考等级的默认配置一样
                 * {@link com.netsdk.lib.enumeration.EM_XRAY_OBJECT_DETECT_CONFIG_LEVEL}
                 */
                System.out.println("emDefaultReferenceLevel:" + info1.emDefaultReferenceLevel);
                /**
                 * 等级名字
                 */
                try {
                    System.out.println("szName:" + new String(info1.szName, encode));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                /**
                 * 物品分组数组个数
                 */
                int nObjectGroupsNum = info1.nObjectGroupsNum;
                NET_XRAY_OBJECT_GROUP[] stuObjectGroups = info1.stuObjectGroups;

                for (int j = 0; j < nObjectGroupsNum; j++) {
                    NET_XRAY_OBJECT_GROUP stuObjectGroup = stuObjectGroups[j];
                    /**
                     * 分组检测使能
                     */
                    System.out.println("bGroupEnable["+j+"]:" + stuObjectGroup.bGroupEnable);
                    /**
                     * 分组类型 {@link com.netsdk.lib.enumeration.EM_INSIDE_OBJECT_TYPE}
                     */
                    System.out.println("分组类型["+j+"]:" + EM_INSIDE_OBJECT_TYPE.getNoteByValue( stuObjectGroup.emGroupType));
                    /**
                     * 分组安全等级 {@link com.netsdk.lib.enumeration.EM_GROUP_GRADE_TYPE}
                     */
                    System.out.println("分组安全等级["+j+"]:" + EM_GROUP_GRADE_TYPE.getNoteByValue(stuObjectGroup.emGroupGrade));
                    /**
                     * 分组物品颜色 {@link com.netsdk.lib.enumeration.EM_GROUP_COLOR_TYPE}
                     */
                    System.out.println("分组物品颜色:" +EM_GROUP_COLOR_TYPE.getNoteByValue(stuObjectGroup.emGroupColor) );

                }

            }

        } else {
            System.out.printf("CLIENT_GetFinancialCabinInfo Failed!LastError = %s\n", ToolKits.getErrorCode());
        }

    }


    public void setXRayMultiLevelDetectCFG() {

        NET_IN_SET_XRAY_MULTILEVEL_DETECT_INFO input = new NET_IN_SET_XRAY_MULTILEVEL_DETECT_INFO();


        int nMultiLevelConfigCnt = stuInfo.nMultiLevelConfigCnt;

        System.out.println("nMultiLevelConfigCnt:" + nMultiLevelConfigCnt);

        NET_MULTI_LEVEL_INFO[] infos = new NET_MULTI_LEVEL_INFO[nMultiLevelConfigCnt];
        for (int i = 0; i < infos.length; i++) {
            infos[i] = new NET_MULTI_LEVEL_INFO();
        }

        ToolKits.GetPointerDataToStructArr(stuInfo.pstuMultiLevelConfig, infos);

        for (int i = 0; i < infos.length; i++) {

            NET_MULTI_LEVEL_INFO info1 = infos[i];

            /**
             * 配置等级 {@link com.netsdk.lib.enumeration.EM_XRAY_OBJECT_DETECT_CONFIG_LEVEL}
             */
            System.out.println("emLevel:" + info1.emLevel);

            /**
             * 默认参考等级，该等级的默认配置与参考等级的默认配置一样
             * {@link com.netsdk.lib.enumeration.EM_XRAY_OBJECT_DETECT_CONFIG_LEVEL}
             */
            System.out.println("emDefaultReferenceLevel:" + info1.emDefaultReferenceLevel);
            /**
             * 等级名字
             */
            try {
                System.out.println("szName:" + new String(info1.szName, encode));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            /**
             * 物品分组数组个数
             */
            int nObjectGroupsNum = info1.nObjectGroupsNum;

            System.out.println("物品分组数组个数:" + nObjectGroupsNum);


            NET_XRAY_OBJECT_GROUP[] stuObjectGroups = info1.stuObjectGroups;

            for (int j = 0; j < nObjectGroupsNum; j++) {
                NET_XRAY_OBJECT_GROUP stuObjectGroup = stuObjectGroups[j];

                /**
                 * 分组类型 {@link com.netsdk.lib.enumeration.EM_INSIDE_OBJECT_TYPE}
                 */
                System.out.println("分组类型["+j+"]:" + EM_INSIDE_OBJECT_TYPE.getNoteByValue( stuObjectGroup.emGroupType));

                if(i==0&&j==0){
                    stuObjectGroup.emGroupType=EM_INSIDE_OBJECT_TYPE.EM_INSIDE_OBJECT_SQUAREKNIFE.getValue();
                }

            }

        }


        ToolKits.SetStructArrToPointerData(infos,stuInfo.pstuMultiLevelConfig);

        input.stuInfo = stuInfo;
        /**
         * 当前配置等级 {@link com.netsdk.lib.enumeration.EM_XRAY_OBJECT_DETECT_CONFIG_LEVEL}
         */
        input.stuInfo.emCurrentLevel = 1;

        Pointer pointerInput = new Memory(input.size());

        pointerInput.clear(input.size());

        ToolKits.SetStructDataToPointer(input, pointerInput, 0);

        NET_OUT_SET_XRAY_MULTILEVEL_DETECT_INFO outPut = new NET_OUT_SET_XRAY_MULTILEVEL_DETECT_INFO();

        Pointer pointerOutput = new Memory(outPut.size());

        pointerOutput.clear(outPut.size());

        ToolKits.SetStructDataToPointer(outPut, pointerOutput, 0);

        NetSDKLib.LLong lLong = netsdk.CLIENT_SetXRayMultiLevelDetectCFG(m_hLoginHandle, pointerInput, pointerOutput,
                3000);

        if (lLong.longValue() != 0) {
            System.out.println("CLIENT_GetFinancialCabinInfo success");
            Native.free(Pointer.nativeValue(pointerInput)); // 清理内存
            Pointer.nativeValue(pointerInput, 0); // 防止gc重复回收

            Native.free(Pointer.nativeValue(pointerOutput));
            Pointer.nativeValue(pointerOutput, 0);

        } else {
            Native.free(Pointer.nativeValue(pointerInput)); // 清理内存
            Pointer.nativeValue(pointerInput, 0); // 防止gc重复回收

            Native.free(Pointer.nativeValue(pointerOutput));
            Pointer.nativeValue(pointerOutput, 0);
            System.out.printf("CLIENT_GetFinancialCabinInfo Failed!LastError = %s\n", ToolKits.getErrorCode());
        }

    }
    public void RunTest()
    {
        System.out.println("Run Test");
        CaseMenu menu = new CaseMenu();;
        menu.addItem(new CaseMenu.Item(this, "订阅报警事件任务", "AttachEventRealLoadPic"));

        menu.addItem(new CaseMenu.Item(this, "退订报警事件任务", "DetachEventRealLoadPic"));

        menu.addItem(new CaseMenu.Item(this, "订阅X光机包裹数量统计信息", "attachPackageStatistics"));

        menu.addItem(new CaseMenu.Item(this, "取消订阅X光机包裹数量统计信息", "DetachPackageStatistics"));

        menu.addItem(new CaseMenu.Item(this, "获取安检机安全等级信息", "getXRayMultiLevelDetectCFG"));

        menu.addItem(new CaseMenu.Item(this, "设置安检机安全等级信息", "setXRayMultiLevelDetectCFG"));

        menu.run();
    }
    // 配置登陆地址，端口，用户名，密码
    private String m_strIpAddr = "10.35.35.54";
    private int m_nPort = 37777;
    private String m_strUser = "admin";
    private String m_strPassword = "admin123";
    public static void main(String[] args) {
        XrayDetectionNewDemo demo=new XrayDetectionNewDemo();
        demo.InitTest();
        demo.RunTest();
        demo.EndTest();

    }

    /**
     * 初始化测试
     */
    public void InitTest() {
        XrayDetectionNewDemo.Init();

        this.loginWithHighLevel();
    }

    /**
     * 结束测试
     */
    public void EndTest() {
        System.out.println("End Test");
        this.logOut(); // 登出设备
        System.out.println("See You...");
        XrayDetectionNewDemo.cleanAndExit(); // 清理资源并退出
    }

}
